﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Giaiphongmatbang.BLL;
using Giaiphongmatbang.UserControl;
using Giaiphongmatbang.DataModel;

namespace Giaiphongmatbang
{
    public partial class quanlynguoidung : System.Web.UI.Page
    {
        QLGPMBEntities db = new QLGPMBEntities();
        DataAccess.GPMBDataContext data = new DataAccess.GPMBDataContext();
        User user;

        protected void Page_Load(object sender, EventArgs e)
        {
            user = (User)Session["User"];
            if (!IsPostBack)
            {
                if (Session["User"] != null)
                {
                    if (!new UserRolesRepository().CheckRoles(user, (int)Utility.Enum.Roles.ManagerAccounts))
                    {
                        Response.Redirect("/duan.aspx");
                    }
                    BindgrvUser();
                }
            }
        }

        protected void BindgrvUser()
        {
            grvUser.DataSource = data.uspUserSearch(txtDisplayName.Text, txtFullName.Text, int.Parse(ddlStatus.SelectedValue));
            grvUser.DataBind();
            if (grvUser.Rows.Count == 0)
            {
                ltrResult.Text = "Không tìm thấy kết quả nào";
            }
            else
            {
                ltrResult.Text = "";
            }
        }
        int userid
        {
            set { ViewState["userid"] = value; }
            get { return (int)ViewState["userid"]; }
        }

        protected void lbtnUser_Click(object sender, EventArgs e)
        {
            LinkButton lbtn = (LinkButton)sender;
            userid = int.Parse(lbtn.CommandArgument);
            User admin = new UserRepository().GetByID(userid);
            if (admin.UserName == "admin" || admin.UserID == 1)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Không thể thay đổi quyền của Admin')", true);
                return;
            }
            btnApply.ValidationGroup = "0";
            checkadd = false;
            pn1.Visible = false;
            pn2.Visible = true;
            setControl(false);
            User objU = new UserRepository().GetByID(userid);
            txtAddress.Text = objU.Address;
            txtFullName.Text = objU.FullName;
            txtUserName.Text = objU.UserName;
            txtDisplayName.Text = objU.DisplayName;
            chkStatus.Checked = objU.isDisable;
            if (objU.CreatedBy != null)
            {
                ltrCreateBy.Text = new UserRepository().GetByID(objU.CreatedBy.Value).FullName;
            }
            else
            {
                ltrCreateBy.Text = "Admin";
            }
            txtEmail.Text = objU.Email;
            txtMatKhau.Text = objU.Password;
            if (objU.Gender)
            {
                ddlGender.SelectedValue = "true";
            }
            else
            {
                ddlGender.SelectedValue = "false";
            }

            txtPhone.Text = objU.PhoneNumber;
            BindgrvRoles();

        }

        protected void BindgrvRoles()
        {
            grvRole.DataSource = new RoleRepository().GetAll();
            grvRole.DataBind();            
        }

        static bool checkadd = false;
        protected void grvRole_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (checkadd)
                return;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                CheckBox chk = (CheckBox)e.Row.FindControl("chk");
                int RoleID = int.Parse(((HiddenField)e.Row.FindControl("hdfRoleID")).Value);
                chk.Checked = db.UserRoles.Any(p => p.User.UserID == userid && p.Role.RoleID == RoleID);
            }
        }

        protected void btnReturn2_Click(object sender, EventArgs e)
        {
            btnApply.ValidationGroup = "1";
            pn1.Visible = true;
            pn2.Visible = false;
        }

        protected void btnApply_Click(object sender, EventArgs e)
        {

            if (!checkadd)
            {
                User u = new UserRepository().GetByID(userid);
                if (u.UserName.Equals("admin"))
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Không thể thay đổi quyền của Admin')", true);
                    return;
                }
                UserRolesRepository repository = new UserRolesRepository();
                int id = ((User)Session["User"]).UserID;
                foreach (GridViewRow item in grvRole.Rows)
                {
                    int RoleID = int.Parse(((HiddenField)item.FindControl("hdfRoleID")).Value);
                    bool chk = ((CheckBox)item.FindControl("chk")).Checked;
                    if (chk)
                    {
                        if (!repository.CheckRoleforUser(userid, RoleID))
                        {
                            repository.Insert(userid, RoleID, id);
                        }
                    }
                    else
                    {
                        if (repository.CheckRoleforUser(userid, RoleID))
                        {
                            repository.DeletebyUserandRole(userid, RoleID);
                        }
                    }

                }
                new UserRepository().isDisable(userid, chkStatus.Checked);
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Cập nhật thành công')", true);
            }
            else
            {
                if (!txtMatKhau.Text.Trim().Equals(txtRePassword.Text.Trim()))
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Nhập lại mật khẩu không đúng!')", true);
                    return;
                }
                if (!new UserRepository().isExists(txtUserName.Text.Trim()))
                {
                    User newU = new User();
                    newU.UserName = txtUserName.Text.Trim();
                    newU.Password = Utility.Encryptions.EncryptUTF8MD5(txtMatKhau.Text);
                    newU.FullName = txtFullName.Text.Trim();
                    newU.DisplayName = txtDisplayName.Text.Trim();
                    newU.Address = txtAddress.Text.Trim();
                    newU.CreatedBy = ((User)Session["User"]).UserID;
                    newU.Email = txtEmail.Text.Trim();
                    newU.Gender = bool.Parse(ddlGender.SelectedValue);
                    newU.PhoneNumber = txtPhone.Text.Trim();
                    newU.isDisable = chkStatus.Checked;
                    db.AddToUsers(newU);
                    db.SaveChanges();

                    UserRolesRepository repository = new UserRolesRepository();
                    int id = ((User)Session["User"]).UserID;
                    foreach (GridViewRow item in grvRole.Rows)
                    {
                        int RoleID = int.Parse(((HiddenField)item.FindControl("hdfRoleID")).Value);
                        bool chk = ((CheckBox)item.FindControl("chk")).Checked;
                        if (chk)
                        {
                            repository.Insert(newU.UserID, RoleID, id);
                        }
                    }
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Thêm mới thành công')", true);
                    Response.Redirect("quanlynguoidung.aspx");
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Tên đăng nhập đã được sử dụng')", true);
                }
            }
        }

        protected void setControl(bool e)
        {
            txtUserName.Enabled = e;
            txtMatKhau.Enabled = e;
            txtFullName.Enabled = e;
            txtDisplayName.Enabled = e;
            txtAddress.Enabled = e;
            txtPhone.Enabled = e;
            txtEmail.Enabled = e;
            ddlGender.Enabled = e;
            
        }

        protected void settxtNull()
        {
            txtUserName.Text = string.Empty;
            txtFullName.Text = string.Empty;
            txtDisplayName.Text = string.Empty;
            txtAddress.Text = string.Empty;
            txtMatKhau.Text = string.Empty;
            txtPhone.Text = string.Empty;
            txtEmail.Text = string.Empty;
            ddlGender.SelectedValue = "true";
            ltrCreateBy.Text = ((User)Session["User"]).FullName;
            foreach (GridViewRow row in grvRole.Rows)
            {
                CheckBox chk = (CheckBox)row.FindControl("chk");
                chk.Checked = false;
            }

            
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            checkadd = true;
            pn1.Visible = false;
            pn2.Visible = true;
            txtAddress.AutoCompleteType = AutoCompleteType.None;
            setControl(true);
            settxtNull();
            txtUserName.Focus();
            BindgrvRoles();
        }

        protected void ddlStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            grvUser.DataSource = data.uspUserSearch(txtDisplayNameSearch.Text, txtFullNameSearch.Text, int.Parse(ddlStatus.SelectedValue));
            grvUser.DataBind();
            if (grvUser.Rows.Count == 0)
            {
                ltrResult.Text = "Không tìm thấy kết quả nào";
            }
            else
            {
                ltrResult.Text = "";
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            grvUser.DataSource = data.uspUserSearch(txtDisplayNameSearch.Text, txtFullNameSearch.Text, int.Parse(ddlStatus.SelectedValue));
            grvUser.DataBind();
            if (grvUser.Rows.Count == 0)
            {
                ltrResult.Text = "Không tìm thấy kết quả nào";
            }
            else
            {
                ltrResult.Text = "";
            }
        }

        protected void btnAll_Click(object sender, EventArgs e)
        {
            txtDisplayNameSearch.Text = "";
            txtFullNameSearch.Text = "";
            ddlStatus.SelectedValue = "0";
            BindgrvUser();
        }

        protected void grvUser_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string command = e.CommandName;
            if (command == "btnDelete")
            {
                int userid = int.Parse(e.CommandArgument.ToString());
                UserRepository objUser = new UserRepository();
                objUser.DeleteByID(userid);
                objUser.Save();
                BindgrvUser();
            }
        }
    }
}